package tugas.akhir.jason;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class HttpClientUtil {
	private static HttpClient httpClient;
	private static final int DEFAULT_HTTP_TIMEOUT = 30000;
	
	public static final ResponseHandler DEFAULT_RESPONSE_HANDLER = new ResponseHandler<String>() {
		BufferedReader contentReader;
		
		public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
			contentReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuilder contentBuilder = new StringBuilder();
			
			String contentLine;
			while((contentLine = contentReader.readLine()) != null) {
				contentBuilder.append(contentLine);
			}
			
			return contentBuilder.toString();
		}
	};
	
	private HttpClientUtil() {}
	
	public static HttpClient getHttpClient() {
		return getHttpClient(DEFAULT_HTTP_TIMEOUT);
	}
	
	public static HttpClient getHttpClient(int timeout) {
		createHttpClientIfNotExists();
		setTimeout(timeout);
		return httpClient;
	}
	
	public static void setTimeout(int timeout) {
		createHttpClientIfNotExists();
		
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
        ConnManagerParams.setTimeout(params, timeout);
	}
	
	private static void createHttpClientIfNotExists() {
		if(httpClient == null) {
			httpClient = new DefaultHttpClient();
		}
	}
	
	public static HttpResponse executePostRequest(String url, List<NameValuePair> requestParams) throws Exception {		
		HttpPost postRequest = new HttpPost(url);
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(requestParams);
		
		postRequest.setEntity(formEntity);
		
		
		
		return getHttpClient().execute(postRequest);
	}	
	public static HttpResponse executePostRequest(String url, List<NameValuePair> requestParams, String username, String password) {
		return null;
	}
	
	public static HttpResponse executeUploadFiles(String url, List<InputStream> fileStreams) {
		HttpPost postRequest = new HttpPost(url);
		
		return null;
	}
	public static HttpResponse executeUploadFiles(String url, List<InputStream> fileStreams, String username, String password) {
		return null;
	}
	
	public static HttpResponse performGetRequest() {
		return null;
	}
}